package com.rachel.pickerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Scroller;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhengshaorui on 2017/7/30.
 */

public class MyPickerView extends View {
    private int mWidth, mHeight;
    private Paint mPaint;
    private List<String> mData = new ArrayList<>();
    private int mVisiableItem = 5;

    private int mBothTextWidth;
    private int mSelectPos;
    private Scroller mScroller;
    private float mMoveLength; //表示滑动的指，最后赋给 textview。
    private GestureDetector mGestureDetector;

    private int mScrollY;

    public MyPickerView(Context context) {
        this(context, null);
    }

    public MyPickerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        for (int i = 2007; i < 2020; i++) {
            mData.add("" + i);
        }
        mSelectPos = mData.size() / 2;

        mScroller = new Scroller(context, new LinearInterpolator());
        mGestureDetector = new GestureDetector(context,
                new FlingGestureListener());
    }

    public MyPickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private float lastY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                break;
            case MotionEvent.ACTION_MOVE:
                if (Math.abs(event.getY() - lastY) < 0.1f) {
                    return true;
                }
                mMoveLength += event.getY() - lastY;
                //mScroller.startScroll(0,mScroller.getCurrY(),0, (int)- mMoveLength);
                lastY = event.getY();

                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                lastY = event.getY();
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            //总共需要滚动的距距离 累加
            mMoveLength = mMoveLength + mScroller.getCurrY() - mScrollY;

            mScrollY = mScroller.getCurrY();
            // checkCirculation(); //　检测当前选中的item
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        for (int i = 1; i < mSelectPos; i++) { //画上面的 text
            drawText(canvas, mSelectPos - i, -i * mBothTextWidth + mMoveLength);
        }

        for (int i = 1; i < mData.size() - mSelectPos; i++) { //画下面的 text
            drawText(canvas, mSelectPos + i, i * mBothTextWidth + mMoveLength);
        }
        drawText(canvas, mData.size() / 2, mMoveLength); //中间
    }

    /**
     * 画文字的方法
     *
     * @param canvas
     * @param position 数据的 positiion
     * @param top      表示与中间基线的距离，即绘制在上面还是在下面，为 mBothTextWidth 的整数倍
     */
    private void drawText(Canvas canvas, int position, float top) {
        String text = mData.get(position);
        int itemSize = mHeight;
        mPaint.setTextSize(30);
        float x = 0;
        float y = 0;
        x = (mWidth - mPaint.measureText(text)) / 2;

        Paint.FontMetrics metrics = mPaint.getFontMetrics();
        float textheight = (metrics.descent + metrics.ascent);
        y = top + itemSize / 2 - textheight / 2;

        canvas.drawText(text, x, y, mPaint);
    }

    /**
     * 快速滑动，滚动一段距离
     */
    class FlingGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            lastY = e.getY();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            //滚动Y初始化
            mScrollY = (int) mMoveLength;

            mScroller.fling(0, (int) mMoveLength, 0, (int) velocityY, 0, 0, -10 * mBothTextWidth,
                    10 * mBothTextWidth);
            invalidate();
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            lastY = e.getY(); //把值重新赋值回去，避免下次按下，坐标偏离
            return true;
        }
    }



    public void cancelScroll() {
        mScrollY = 0;


        mScroller.abortAnimation();
        // stopAutoScroll();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        mBothTextWidth = mHeight / mVisiableItem;

    }
}
